package cn.hx.controller.system;

import cn.hx.entity.News;
import cn.hx.entity.NewsDetail;
import cn.hx.entity.UserInfo;
import cn.hx.service.NewsDetailService;
import cn.hx.service.NewsService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 新闻(News)表控制层
 *
 * @author makejava
 * @since 2022-08-20 15:47:51
 */
@Controller
public class NewsController {
    /**
     * 服务对象
     */
    @Resource
    private NewsService newsService;
    @Resource
    private NewsDetailService newsDetailService;

    @GetMapping("system/news/newsList")
    public String newListPage(
            ModelMap modelMap,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "9") int size) {
        modelMap.addAttribute("newListPage", newsService.page(page, size));
        return "system/news/newsList";
    }

    @GetMapping("system/news/deleteNew/{id}")
    public String delete(@PathVariable Integer id) {
        newsService.deleteById(id);
        return "redirect:/system/news/newsList";
    }

    @PostMapping("system/news/newsEdit")
    @ResponseBody
    public Map saveUser(News news, String content, HttpSession session) {
        HashMap<Object, Object> map = new HashMap<>();
        if (news.getId().equals(-1)) {
            NewsDetail newsDetail = new NewsDetail();
            newsDetail.setContent(content);
            newsDetailService.insert(newsDetail);

            news.setNewsDetail(newsDetail);
            UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");


            news.setUserInfo(userInfo);
            newsService.insert(news);

            map.put("code","0");
            map.put("msg","新增成功");
        }else{
            newsService.update(news);

            NewsDetail newsDetail = new NewsDetail();
            newsDetail.setId(news.getNewsDetailId());
            newsDetail.setContent(content);
            System.out.println(content);
            newsDetailService.update(newsDetail);
            map.put("code","0");
            map.put("msg","修改成功");
        }
        return map;
    }

    @GetMapping("system/news/newsEdit1/{id}")
    public String update(@PathVariable Integer id, ModelMap modelMap) {
        modelMap.addAttribute("news", newsService.queryById(id));
        return "system/news/newsEdit1";
    }

    @PostMapping("system/news/newsEdit/{id}")
    public String editCar(News news) {
        newsService.update(news);
        return "redirect:/system/news/newsList";
    }


    @GetMapping("system/news/newsContent/{id}")
    public String newsContent(@PathVariable Integer id, ModelMap modelMap) {
        modelMap.addAttribute("news", newsService.queryById(id));
        return "system/news/newsContent";
    }
}